package middleware

import (
    "net/http"
    "github.com/gin-gonic/gin"
    "github.com/afex/hystrix-go/hystrix"
)

func CircuitBreakerMiddleware(name string) gin.HandlerFunc {
    return func(c *gin.Context) {
        hystrix.ConfigureCommand(name, hystrix.CommandConfig{
            Timeout:               1000,
            MaxConcurrentRequests: 100,
            RequestVolumeThreshold: 20,
            SleepWindow:            5000,
            ErrorPercentThreshold:  50,
        })

        hystrix.Go(name, func() error {
            c.Next()
            return nil
        }, func(err error) error {
            c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "Service temporarily unavailable"})
            return nil
        })
    }
}